﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using OpusSuite.Models;
using OpusSuite.Models.Model.Ref;
using System.Web.UI;

//using MvcMiniProfiler;

namespace OpusSuite.Controllers
{
	public class RefController : BaseController
	{
		public PartialViewResult CountrySelect(string code)
		{
			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

			try
			{
                return PartialView(model.Context.Countries.FirstOrDefault(x => x.Code == code));
			}
			catch (Exception e)
			{
				ModelState.AddModelError("Error", "Unable to load country: " + e.Message);
			}

			return PartialView();
		}

		public JsonResult CountrySelectData(string sidx, string sord, int page, int rows)
		{
			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

			int pageIndex = Convert.ToInt32(page) - 1;
			int pageSize = rows;
		    IQueryable<Country> countries;

			if (sord.ToLower() == "desc")
			{
				switch (sidx.ToLower())
				{
					case "code":
						countries = model.Context.Countries.OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        countries = model.Context.Countries.OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "language":
                        countries = model.Context.Countries.OrderByDescending(c => c.Language).Skip(pageIndex * pageSize).Take(pageSize);
						break;
					
					default:
                        countries = model.Context.Countries.OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}
			else
			{
				switch (sidx.ToLower())
				{
					case "code":
                        countries = model.Context.Countries.OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        countries = model.Context.Countries.OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "language":
                        countries = model.Context.Countries.OrderBy(c => c.Language).Skip(pageIndex * pageSize).Take(pageSize);
						break;
					
					default:
                        countries = model.Context.Countries.OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}

            int totalRecords = countries.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast

            var jsonData = new
            {
				total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
				page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
				records = totalRecords,
				rows = (
				  from country in countries
				  select new
				  {
					  id = country.Code,
					  cell = new [] { 
						"", country.Code, country.Description, country.Language.Name, country.MoneyFormat.Name, country.DateFormat.Name, country.Language.Code, country.MoneyFormat.Code, country.DateFormat.Code
					  }
				  }).ToArray()
			}; 

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}

		public PartialViewResult LanguageSelect(int id)
		{
            //var profiler = MiniProfiler.Current; // it's ok if this is null

			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

			try
			{
                Language l = model.Context.Languages.FirstOrDefault(x => x.Id == id);
                if (l != null)
                {
                    ViewBag.Id = l.Id;
                    return PartialView(l);
                }
			}
			catch (Exception e)
			{
				ModelState.AddModelError("Error", "Unable to load language: " + e.Message);
			}

            ViewBag.Id = 0;
			return PartialView();
		}

        public JsonResult LanguageCodeAvailable(string code="")
        {
            try
            {
                OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

                Language l = model.Context.Languages.FirstOrDefault(x => x.Code == code);

                if (l!=null && l.Code == code)
                    return Json("The language code " + code + " has already been used.", JsonRequestBehavior.AllowGet);
                    // TODO model.AddValidationMessage("The language code " + code + " has already been used.", "The language code " + code + " has already been used.");
            }
            catch
            {
                // do nothing..
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true, Duration=0)]
        public JsonResult LanguageSelectSave(Language l)
        {
            bool ok = true;
            int id = 0;
            string code = "";
            string name = "";
            string desc = "";
            Utility.Enums.ApplicationMessageLevel level = Utility.Enums.ApplicationMessageLevel.Information;

            try
            {
                OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());
                string message;
                string description;

                if (l != null)
                {

                    if (string.IsNullOrWhiteSpace(l.Code) || string.IsNullOrWhiteSpace(l.Name) ||
                        string.IsNullOrWhiteSpace(l.Description))
                    {
// ReSharper disable RedundantAssignment
                        message = string.Format("Validation failed for language {0}", l.Name);
                        description = string.Format("Validation failed for langauge {0}: {1}", l.Name,
                                                    "Please make sure all required fields are present.");
                        // ReSharper restore RedundantAssignment
                        level = Utility.Enums.ApplicationMessageLevel.Error;
                        ok = false;
                    }

                    if (l.Id == 0)
                    {
                        try
                        {
                            model.Context.Languages.Add(l);
                            model.Context.SaveChanges();

                            message = string.Format("Language {0} added successfully.", l.Name);
                            description = string.Format("Language {0} added successfully.", l.Name);
                            id = l.Id;
                            code = l.Code;
                            name = l.Name;
                            desc = l.Description;
                        }
                        catch (Exception e)
                        {
                            message = string.Format("Cannot add language {0}", l.Name);
                            description = string.Format("Cannot add langauge {0}: {1}", l.Name, e.Message);
                            level = Utility.Enums.ApplicationMessageLevel.Error;
                            ok = false;
                        }
                    }
                    else
                    {
                        try
                        {
                            Language language = model.Context.Languages.FirstOrDefault(x => x.Id == l.Id);
                            model.Context.Entry(language).CurrentValues.SetValues(l);
                            model.Context.SaveChanges();

                            message = string.Format("Language {0} updated successfully.", l.Name);
                            description = string.Format("Language {0} updated successfully.", l.Name);
                            id = l.Id;
                            code = l.Code;
                            name = l.Name;
                            desc = l.Description;
                        }
                        catch (Exception e)
                        {
                            message = string.Format("Cannot update language {0}", l.Name);
                            description = string.Format("Cannot update langauge {0}: {1}", l.Name, e.Message);
                            level = Utility.Enums.ApplicationMessageLevel.Error;
                            ok = false;
                        }
                    }
                }
                else
                {
                    message = string.Format("Cannot update language {0}", "null");
                    description = string.Format("Cannot update langauge {0}", "null");
                    level = Utility.Enums.ApplicationMessageLevel.Error;
                    ok = false;
                }

                model.AddApplicationMessage(
                    Utility.Enums.ApplicationMessageType.Message,
                    level,
                    message,
                    description,
                    model.Context.Users.FirstOrDefault(x => x.UserName == User.Identity.Name));
            }
            catch
            {
                // we cant do anything as we are in an ajax request so the connection should
                // have been valid
                ok=false;   
            }

            return Json(new { Success = ok, Id = id, Code = code, Name = name, Description = desc });
        }

        [HttpPost]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true, Duration = 0)]
        public JsonResult LanguageSelectDelete(Language l)
        {
            bool ok = true;
            Utility.Enums.ApplicationMessageLevel level = Utility.Enums.ApplicationMessageLevel.Information;

            try
            {
                OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(),
                                                          Utility.WebUtil.ConnectionStringFromCookie());

                string message;
                string description;
                if (l != null)
                {

                    if (string.IsNullOrWhiteSpace(l.Code) || string.IsNullOrWhiteSpace(l.Name) ||
                        string.IsNullOrWhiteSpace(l.Description))
                    {
// ReSharper disable RedundantAssignment
                        message = string.Format("Validation failed for language {0}", l.Name);
                        description = string.Format("Validation failed for langauge {0}: {1}", l.Name,
                                                    "Please make sure all required fields are present.");
// ReSharper restore RedundantAssignment
                        level = Utility.Enums.ApplicationMessageLevel.Error;
                        ok = false;
                    }

                    try
                    {
                        model.Context.Languages.Remove(l);
                        model.Context.SaveChanges();

                        message = string.Format("Language {0} removed successfully.", l.Name);
                        description = string.Format("Language {0} removed successfully.", l.Name);
                    }
                    catch (Exception e)
                    {
                        message = string.Format("Cannot remove language {0}", l.Name);
                        description = string.Format("Cannot remove langauge {0}: {1}", l.Name, e.Message);
                        level = Utility.Enums.ApplicationMessageLevel.Error;
                        ok = false;
                    }

                }
                else
                {
                    message = string.Format("Validation failed for language {0}", "null");
                    description = string.Format("Validation failed for langauge {0}: {1}", "null",
                                                "Please make sure all required fields are present.");
                    level = Utility.Enums.ApplicationMessageLevel.Error;
                    ok = false;
                }

                model.AddApplicationMessage(
                    Utility.Enums.ApplicationMessageType.Message,
                    level,
                    message,
                    description,
                    model.Context.Users.FirstOrDefault(x => x.UserName == User.Identity.Name));
            }
            catch
            {
                // we cant do anything as we are in an ajax request so the connection should
                // have been valid
                ok = false;
            }

            return Json(new { Success = ok });
        }

		public JsonResult LanguageSelectData(int id, string code, string name, string description, string sidx, string sord, int page, int rows)
		{
			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
		    IQueryable<Language> languages;

			if (sord.ToLower() == "desc")
			{
				switch (sidx.ToLower())
				{
					case "code":
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderByDescending(c => c.Code)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
						break;

					case "description":
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderByDescending(c => c.Description)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
						break;

                    default:
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderByDescending(c => c.Name)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
                        break;

                }
			}
			else
			{
				switch (sidx.ToLower())
				{
					case "code":
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderBy(c => c.Code)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
						break;

					case "description":
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderBy(c => c.Description)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
						break;

					default:
                        languages = model.Context.Languages
                            .Where((x => x.Id == id || id == 0))
                            .Where((x => x.Code == code || code.Length == 0))
                            .Where((x => x.Name == name || name.Length == 0))
                            .Where((x => x.Description == description || description.Length == 0))
                            .OrderBy(c => c.Name)
                            .Skip(pageIndex * pageSize)
                            .Take(pageSize);
						break;
				}
			}

            int totalRecords = languages.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast

			var jsonData = new
			{
				total =  totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
				page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
				records = totalRecords,
				rows = (
				  from language in languages
				  select new
				  {
					  id = language.Code,
					  cell = new [] { 
						language.Id.ToString(CultureInfo.CurrentCulture), language.Code, language.Name, language.Description
					  }
				  }).ToArray()
			};

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}

        [HttpGet]
        public JsonResult Language(int id)
        {
            OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            Language l = model.Context.Languages.FirstOrDefault(x => x.Id == id);

            return Json(l, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public JsonResult Countries(string sidx, int page, string sord, int rows, string searchTerm)
        {
            OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = model.Context.Languages.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast
            IQueryable<Country> countries;

            if (sord.ToLower() == "desc")
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }
            else
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        countries = model.Context.Countries.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }

            var jsonData = new
            {
                total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
                page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
                records = totalRecords,
                rows = (
                  from country in countries
                  select new
                  {
                      id = country.Id,
                      code = country.Code,
                      name = "",
                      description = country.Description

                  }).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult Languages(string sidx, int page, string sord, int rows, string searchTerm)
        {
            OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = model.Context.Languages.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast
            IQueryable<Language> languages;

            if (sord.ToLower() == "desc")
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }
            else
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        languages = model.Context.Languages.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }

            var jsonData = new
            {
                total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
                page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
                records = totalRecords,
                rows = (
                  from language in languages
                  select new
                  {
                      id = language.Id,
                      code= language.Code,
                      name = language.Name,
                      description = language.Description
					  
                  }).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult MoneyFormats(string sidx, int page, string sord, int rows, string searchTerm)
        {
            OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = model.Context.MoneyFormats.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast
            IQueryable<MoneyFormat> moneyFormats;

            if (sord.ToLower() == "desc")
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }
            else
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        moneyFormats = model.Context.MoneyFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }

            var jsonData = new
            {
                total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
                page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
                records = totalRecords,
                rows = (
                  from format in moneyFormats
                  select new
                  {
                      id = format.Id,
                      code = format.Code,
                      name = format.Name,
                      description = format.Description

                  }).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult DateFormats(string sidx, int page, string sord, int rows, string searchTerm)
        {
            OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = model.Context.DateFormats.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast
            IQueryable<DateFormat> dateFormats;

            if (sord.ToLower() == "desc")
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }
            else
            {
                switch (sidx.ToLower())
                {
                    case "code":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "name":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    case "description":
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
                        break;

                    default:
                        dateFormats = model.Context.DateFormats.Where(x => x.Description.Contains(searchTerm)).OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
                        break;
                }
            }

            var jsonData = new
            {
                total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
                page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
                records = totalRecords,
                rows = (
                  from format in dateFormats
                  select new
                  {
                      id = format.Id,
                      code = format.Code,
                      name = format.Name,
                      description = format.Description

                  }).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        
        public PartialViewResult DateFormatSelect()
		{
			//OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());
			//ViewBag.Countries = model.DateFormats();

			return PartialView();
		}

		public JsonResult DateFormatSelectData(string sidx, string sord, int page, int rows)
		{
			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

			int pageIndex = Convert.ToInt32(page) - 1;
			int pageSize = rows;
		    IQueryable<DateFormat> formats;

			if (sord.ToLower() == "desc")
			{
				switch (sidx.ToLower())
				{
					case "code":
                        formats = model.Context.DateFormats.OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        formats = model.Context.DateFormats.OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "name":
                        formats = model.Context.DateFormats.OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					default:
                        formats = model.Context.DateFormats.OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}
			else
			{
				switch (sidx.ToLower())
				{
					case "code":
                        formats = model.Context.DateFormats.OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        formats = model.Context.DateFormats.OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "name":
                        formats = model.Context.DateFormats.OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					default:
                        formats = model.Context.DateFormats.OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}

            int totalRecords = formats.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast

            var jsonData = new
			{
				total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
				page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
				records = totalRecords,
				rows = (
				  from format in formats
				  select new
				  {
					  id = format.Code,
					  cell = new [] { 
						"", format.Code, format.Name, format.Description
					  }
				  }).ToArray()
			};

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}

		public PartialViewResult MoneyFormatSelect()
		{
			//OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());
			//ViewBag.Countries = model.MoneyFormats();

			return PartialView();
		}

		public JsonResult MoneyFormatSelectData(string sidx, string sord, int page, int rows)
		{
			OpusSuiteModel model = new OpusSuiteModel(Utility.WebUtil.ServerTypeFromCookie(), Utility.WebUtil.ConnectionStringFromCookie());

			int pageIndex = Convert.ToInt32(page) - 1;
			int pageSize = rows;
		    IQueryable<MoneyFormat> formats;

			if (sord.ToLower() == "desc")
			{
				switch (sidx.ToLower())
				{
					case "code":
                        formats = model.Context.MoneyFormats.OrderByDescending(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        formats = model.Context.MoneyFormats.OrderByDescending(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "name":
                        formats = model.Context.MoneyFormats.OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					default:
                        formats = model.Context.MoneyFormats.OrderByDescending(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}
			else
			{
				switch (sidx.ToLower())
				{
					case "code":
                        formats = model.Context.MoneyFormats.OrderBy(c => c.Code).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "description":
                        formats = model.Context.MoneyFormats.OrderBy(c => c.Description).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					case "name":
                        formats = model.Context.MoneyFormats.OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;

					default:
                        formats = model.Context.MoneyFormats.OrderBy(c => c.Name).Skip(pageIndex * pageSize).Take(pageSize);
						break;
				}
			}

            int totalRecords = formats.Count();
// ReSharper disable RedundantCast
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// ReSharper restore RedundantCast

            var jsonData = new
			{
				total = totalPages,
// ReSharper disable RedundantAnonymousTypePropertyName
				page = page,
// ReSharper restore RedundantAnonymousTypePropertyName
				records = totalRecords,
				rows = (
				  from format in formats
				  select new
				  {
					  id = format.Code,
					  cell = new [] { 
						"", format.Code, format.Name, format.Description
					  }
				  }).ToArray()
			};

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}
	}
}
